import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import './index.scss'
import loginBg from '../../../public/19.png'
import logo from '../../../public/19.png'
import passwordIcon from '../../../public/9.png'
import emailIcon from '../../../public/10.png'
import eyeIcon from '../../../public/37.png'
import eyeCloseIcon from '../../../public/38.png'
import BottomImg from '../../../public/容器底部.png'
import { Wechat } from '@react-vant/icons'
import encryptWithRSA from '../../utils/encryptWithRSA'
import { login } from '../../api/index.ts'
import { Toast } from 'antd-mobile'
import { useUser } from '../../hooks/useUser'
import { logStoredUserInfo } from '../../utils/localStorageUtils'

const Login: React.FC = () => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [errors, setErrors] = useState<{ email?: string; password?: string }>({})
  const navigate = useNavigate()

  // 使用用户状态管理
  const { handleLoginSuccess, setUserLoading, loading } = useUser()

  const PUBLIC_KEY = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`
  const payload = {
    email: email,
    pwd: encryptWithRSA(password, PUBLIC_KEY)
  }

  const validate = () => {
    const next: { email?: string; password?: string } = {}
    if (!email.trim()) {
      next.email = '邮箱不能为空'
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      next.email = '请输入有效的邮箱地址'
    }
    if (!password.trim()) {
      next.password = '密码不能为空'
    } else if (password.trim().length < 6) {
      next.password = '密码不能少于6位'
    }
    setErrors(next)
    return Object.keys(next).length === 0
  }

  const handleLogin = async () => {
    if (!validate()) return
    try {
      // 设置加载状态
      setUserLoading(true)

      // 这里添加登录逻辑
      console.log('登录:', { email, password })

      const res = await login(payload.email, payload.pwd)
      console.log(res);

      if (res.status === 200) {
        Toast.show({
          content: '登录成功',
        })

        // 将用户数据存储到Redux store中
        const userInfo = res.data.result
        handleLoginSuccess(userInfo)

        // 直接存储Token和User ID到localStorage
        localStorage.setItem('token', userInfo.sessionId || '')
        localStorage.setItem('userId', userInfo.userId?.toString() || '')
        localStorage.setItem('userInfo', JSON.stringify(userInfo))

        // 打印用户信息以便调试
        console.log('用户信息已存储到store:', {
          userId: userInfo.userId,
          nickName: userInfo.nickName,
          email: userInfo.email,
          sessionId: userInfo.sessionId
        });
        
        console.log('Token和User ID已直接存储到localStorage:');
        console.log('Token:', localStorage.getItem('token'));
        console.log('User ID:', localStorage.getItem('userId'));
        
        // 延迟一点时间确保Redux Persist完成存储，然后验证本地存储
        setTimeout(() => {
          console.log('验证本地存储中的用户信息:');
          logStoredUserInfo();
        }, 100);
        
        navigate('/home3')
      } else {
        Toast.show({
          content: '登录失败，请检查邮箱和密码',
        })
      }
    } catch (error) {
      console.error('登录错误:', error)
      Toast.show({
        content: '登录失败，请稍后重试',
      })
    } finally {
      // 清除加载状态
      setUserLoading(false)
    }
  }

  const handleRegister = () => {
    navigate('/zc')
  }

  const handleForgotPassword = () => {
    // 跳转到忘记密码页面
    navigate('/wjmm')
  }

  return (
    <div className='loginPage'>
      <div className='background'>
        <img src={loginBg} alt="登录背景" className='bgImage' />
      </div>

      <div className='content'>
        {/* Logo区域 */}
        <div className='logoSection'>
          <div className='logo'>
            <div className='logoIcon'>
              <div className='heartIcon'><img src={logo} alt='' className='logoImg' /></div>
            </div>
          </div>
        </div>

        {/* 登录表单 */}
        <div className='loginCard'>
          <div className='inputGroup'>
            <div className='inputWrapper'>
              <div className='inputIcon'><img src={emailIcon} alt="email" /></div>
              <input
                type="email"
                placeholder="请输入邮箱"
                value={email}
                onChange={(e) => { setEmail(e.target.value); if (errors.email) setErrors(prev => ({ ...prev, email: undefined })) }}
                onBlur={() => validate()}
                className={`input ${errors.email ? 'inputError' : ''}`}
              />
            </div>
            {errors.email && <div className='errorMsg'>{errors.email}</div>}

            <div className='inputWrapper'>
              <div className='inputIcon'><img src={passwordIcon} alt="password" /></div>
              <input
                type={showPassword ? 'text' : 'password'}
                placeholder="请输入密码"
                value={password}
                onChange={(e) => { setPassword(e.target.value); if (errors.password) setErrors(prev => ({ ...prev, password: undefined })) }}
                onBlur={() => validate()}
                className={`input ${errors.password ? 'inputError' : ''}`}
              />
              <button
                type="button"
                className='eyeIcon'
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? <img src={eyeIcon} alt="" /> : <img src={eyeCloseIcon} alt="" />}
              </button>
            </div>
          </div>
          <button
            className='loginButton'
            onClick={handleLogin}
            disabled={loading}
          >
            {loading ? '登录中...' : '登录'}
          </button>
        </div>
        <img src={BottomImg} alt="" className='BottomImg' />
        <div className='links'>
          <button className='link' onClick={handleForgotPassword}>
            忘记密码
          </button>
          <button className='link' onClick={handleRegister}>
            <span className='linkText'>暂无账号?</span>
            <span className='linkText2'>立即注册</span>
          </button>
        </div>
        {/* 其他登录方式 */}
        <div className='otherLogin'>
          <div className='divider'>
            <span className='dividerText'>其它登录方式</span>
          </div>
          <div className='socialLogin'>
            <button className='socialButton'>
              <div className='wechatIcon'>
                <Wechat />
              </div>
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Login